/*

 * Copyright (C) 2021 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */
package org.zakariya.flyoutmenudemo.slice;

import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.Element;
import ohos.agp.components.element.ElementScatter;
import ohos.agp.components.element.PixelMapElement;
import ohos.agp.window.service.WindowManager;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;
import ohos.multimodalinput.event.TouchEvent;
import org.zakariya.flyoutmenu.ColorUtils;
import org.zakariya.flyoutmenu.FlyoutMenuView;
import org.zakariya.flyoutmenudemo.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import org.zakariya.flyoutmenudemo.menus.EmojiFlyoutMenu;
import org.zakariya.flyoutmenudemo.menus.IconFlyoutMenu;
import org.zakariya.flyoutmenudemo.menus.PaletteFlyoutMenu;
import org.zakariya.flyoutmenudemo.menus.ToolFlyoutMenu;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MainAbilitySlice extends AbilitySlice {

    private static float BRUSH_SCALE = 16;

    FlyoutMenuView smileyFlyoutMenu;
    FlyoutMenuView iconFlyoutMenu;
    FlyoutMenuView toolSelectorFlyoutMenu;
    FlyoutMenuView paletteFlyoutMenu;
    Text brushStateTextView;
    int smileyFlyoutMenuSelectionId = 0;
    int iconFlyoutMenuSelectionId = 0;
    int paletteFlyoutMenuSelectionId = 0;
    int  toolFlyoutMenuSelectionId = 1;
    float brushSize;
    boolean brushIsEraser;
    int brushColor;

    @Override
    public void onStart(Intent intent) {
        WindowManager.getInstance().getTopWindow().get().setStatusBarColor(new RgbColor(48, 62, 157).asArgbInt());
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        DependentLayout dependentLayout = (DependentLayout) findComponentById(ResourceTable.Id_parent_root);
        smileyFlyoutMenu = (FlyoutMenuView) findComponentById(ResourceTable.Id_smileyFlyoutMenu);
        iconFlyoutMenu = (FlyoutMenuView) findComponentById(ResourceTable.Id_iconFlyoutMenu);
        paletteFlyoutMenu  = (FlyoutMenuView) findComponentById(ResourceTable.Id_paletteFlyoutMenu);
        toolSelectorFlyoutMenu = (FlyoutMenuView) findComponentById(ResourceTable.Id_toolSelectorFlyoutMenu);
        brushStateTextView = (Text) findComponentById(ResourceTable.Id_brushStateTextView);

        configureSmileyFlyoutMenu();
        configureIconFlyoutMenu();
        configurePaletteFlyoutMenu();
        configureToolFlyoutMenu();

        smileyFlyoutMenu.setSelectedMenuItemById(smileyFlyoutMenuSelectionId);
        iconFlyoutMenu.setSelectedMenuItemById(iconFlyoutMenuSelectionId);
//        toolSelectorFlyoutMenu.setSelectedMenuItemById(paletteFlyoutMenuSelectionId);
        toolSelectorFlyoutMenu.setSelectedMenuItemById(0);
        paletteFlyoutMenu.setSelectedMenuItemById(0);

        dependentLayout.setTouchEventListener(new Component.TouchEventListener() {
            @Override
            public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
               if(touchEvent.getAction() == TouchEvent.PRIMARY_POINT_DOWN) {
                    smileyFlyoutMenu.detachMenuOverlayView();
                    iconFlyoutMenu.detachMenuOverlayView();
                    paletteFlyoutMenu.detachMenuOverlayView();
                    toolSelectorFlyoutMenu.detachMenuOverlayView();
                   iconFlyoutMenu.invalidate();
                }
                return true;
            }
        });
    }

    void configureIconFlyoutMenu() {
        List<FlyoutMenuView.MenuItem> menuItems = new ArrayList<>();
        int[] drawables = {
                ResourceTable.Graphic_ic_ohos_black_24dp,
                ResourceTable.Graphic_ic_ac_unit_black_24dp,
                ResourceTable.Graphic_ic_airport_shuttle_black_24dp,
        };
        int[] pixelables = {
                ResourceTable.Media_cat
        };

        for (int i =0;i<drawables.length;i++) {
            Element drawable = null;//getResources().getDrawable(drawableId);

            drawable  = ElementScatter.getInstance(this).parse(drawables[i]);
            menuItems.add(new IconFlyoutMenu.MenuItem(getContext(),i, drawable, 10));
        }

        for(int j = 0;j < pixelables.length;j++) {
            Element pixelmapElement = null;
            try {
                pixelmapElement = new PixelMapElement(getResourceManager().getResource(pixelables[j]));
            } catch (IOException e) {
                e.printStackTrace();
            } catch (NotExistException e) {
                e.printStackTrace();
            }

            menuItems.add(new IconFlyoutMenu.MenuItem(getContext(),drawables.length+j, pixelmapElement, 10));
        }

        iconFlyoutMenu.setLayout(new FlyoutMenuView.GridLayout(2, FlyoutMenuView.GridLayout.UNSPECIFIED));
        iconFlyoutMenu.setAdapter(new FlyoutMenuView.ArrayAdapter<>(menuItems));

        IconFlyoutMenu.ButtonRenderer renderer;
            renderer = new IconFlyoutMenu.ButtonRenderer(
                    ElementScatter.getInstance(this).parse(ResourceTable.Graphic_ic_ohos_black_24dp),
//                    new PixelMapElement(ImageSource.create(getResourceManager().getResource(ResourceTable.Graphic_ic_ohos_black_24dp), new ImageSource.SourceOptions()).createPixelmap(null)),
                    10);
            iconFlyoutMenu.setButtonRenderer(renderer);

            iconFlyoutMenu.setSelectionListener(new FlyoutMenuView.SelectionListener() {
                @Override
                public void onItemSelected(FlyoutMenuView flyoutMenuView, FlyoutMenuView.MenuItem item) {
                    iconFlyoutMenuSelectionId = item.getId();
                    renderer.setIcon(((IconFlyoutMenu.MenuItem) item).getIcon());
                }

                @Override
                public void onDismissWithoutSelection(FlyoutMenuView flyoutMenuView) {
                }
            });
    }

    void configureToolFlyoutMenu() {

//        float alphaCheckerSize = getResources().getDimension(R.dimen.alpha_checker_size);
//        int toolColor = ContextCompat.getColor(this, R.color.toolFillColor);
//        int alphaCheckerColor = ContextCompat.getColor(this, R.color.alphaCheckerColor);
//        float toolInset = getResources().getDimension(R.dimen.tool_button_inset);


        final int count = 6;
        List<FlyoutMenuView.MenuItem> items = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            float size = (float) (i + 1) / (float) count;
            items.add(new ToolFlyoutMenu.MenuItem(getContext(),i, size, false, 15,0xFFD6D6D6, 0xFF303030));
        }

        for (int i = 0; i < count; i++) {
            float size = (float) (i + 1) / (float) count;
            items.add(new ToolFlyoutMenu.MenuItem(getContext(),count+i, size, true, 15,0xFFD6D6D6, 0xFF303030));
        }


        toolSelectorFlyoutMenu.setLayout(new FlyoutMenuView.GridLayout(count, FlyoutMenuView.GridLayout.UNSPECIFIED));
        toolSelectorFlyoutMenu.setAdapter(new FlyoutMenuView.ArrayAdapter<>(items));
        toolSelectorFlyoutMenu.setData(items);

        final ToolFlyoutMenu.ButtonRenderer toolButtonRenderer = new ToolFlyoutMenu.ButtonRenderer(10, 1, false, 15,0xFFD6D6D6, 0xFF303030);
        toolSelectorFlyoutMenu.setButtonRenderer(toolButtonRenderer);

        toolSelectorFlyoutMenu.setSelectionListener(new FlyoutMenuView.SelectionListener() {
            @Override
            public void onItemSelected(FlyoutMenuView flyoutMenuView, FlyoutMenuView.MenuItem item) {
                toolFlyoutMenuSelectionId = item.getId();

//                toolSelectorFlyoutMenu.setSelectedMenuItemById(toolFlyoutMenuSelectionId);
                ToolFlyoutMenu.MenuItem toolMenuItem = (ToolFlyoutMenu.MenuItem) item;

                toolButtonRenderer.setSize(toolMenuItem.getSize());
                toolButtonRenderer.setIsEraser(toolMenuItem.isEraser());
                toolSelectorFlyoutMenu.setButtonRenderer(toolButtonRenderer);
                setBrushSize(toolMenuItem.getSize() * BRUSH_SCALE);
                setBrushIsEraser(toolMenuItem.isEraser());
            }

            @Override
            public void onDismissWithoutSelection(FlyoutMenuView flyoutMenuView) {
            }
        });
    }


    void configurePaletteFlyoutMenu() {

        int cols = 8;
        int rows = 8;
        double[] hsl = {0, 0, 0};
        double cornerRadius = 0;
        if (paletteFlyoutMenu.getItemMargin() > 0) {
            cornerRadius = 4;//TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4f, getResources().getDisplayMetrics());
        }

        paletteFlyoutMenu.setLayout(new FlyoutMenuView.GridLayout(cols, FlyoutMenuView.GridLayout.UNSPECIFIED));

        List<FlyoutMenuView.MenuItem> items = new ArrayList<>();
        for (int r = 0; r < rows; r++) {
            float hue = 360f * ((float) r / (float) rows);
            hsl[0] = hue;
            for (int c = 0; c < cols; c++) {
                if (c == 0) {
                    float lightness = (float) r / (float) (rows - 1);
                    hsl[1] = 0;
                    hsl[2] = lightness;
                } else {
                    float lightness = (float) c / (float) cols;
                    hsl[1] = 1;
                    hsl[2] = lightness;
                }
                int z = r == 0?c:r*8+c;
                items.add(new PaletteFlyoutMenu.MenuItem(getContext(),z, ColorUtils.HSLToColor(hsl), cornerRadius,r,c));
            }
        }
//        paletteFlyoutMenu.setData(items);
        paletteFlyoutMenu.setAdapter(new FlyoutMenuView.ArrayAdapter<>(items));

        float inset = 10;//getResources().getDimension(R.dimen.palette_swatch_inset);
        final PaletteFlyoutMenu.ButtonRenderer renderer = new PaletteFlyoutMenu.ButtonRenderer(inset);
        paletteFlyoutMenu.setButtonRenderer(renderer);

        paletteFlyoutMenu.setSelectionListener(new FlyoutMenuView.SelectionListener() {
            @Override
            public void onItemSelected(FlyoutMenuView flyoutMenuView, FlyoutMenuView.MenuItem item) {
                paletteFlyoutMenuSelectionId = item.getId();
                int color = ((PaletteFlyoutMenu.MenuItem) item).getColor();
                renderer.setCurrentColor(color);
                setBrushColor(color);
            }

            @Override
            public void onDismissWithoutSelection(FlyoutMenuView flyoutMenuView) {
            }
        });
    }


    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    void configureSmileyFlyoutMenu() {

        String[] emojiCodes = {
                "1f60d", "1f605", "1f60a",
                "1f613", "1f61e", "1f620",
                "1f62d", "1f4a9",
        };
//        final boolean canUseEmoji = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;


        ohos.global.resource.ResourceManager resManager = this.getResourceManager();

        float fontSizeInMenu = 0;
        float fontSizeInButton = 0;
        int color = 0;
        try {
            color = resManager.getElement(ResourceTable.Color_smileyMenuCharColor).getInteger();
            fontSizeInMenu = resManager.getElement(ResourceTable.Float_smiley_menu_item_size).getFloat() * 2.0f;
            fontSizeInButton = resManager.getElement(ResourceTable.Float_flyout_menu_button_size).getFloat() * 0.5f;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotExistException e) {
            e.printStackTrace();
        } catch (WrongTypeException e) {
            e.printStackTrace();
        }


        List<FlyoutMenuView.MenuItem> menuItems = new ArrayList<>();

        for (int i = 0; i < emojiCodes.length; i++) {
//            int code = charCodes[i];//canUseEmoji ? emojiCodes[i] : charCodes[i];
            menuItems.add(new EmojiFlyoutMenu.MenuItem(getContext(),i, emojiCodes[i], fontSizeInMenu, color));
        }

//        smileyFlyoutMenu.setData(menuItems);
        smileyFlyoutMenu.setLayout(new FlyoutMenuView.GridLayout(2, FlyoutMenuView.GridLayout.UNSPECIFIED));
        smileyFlyoutMenu.setAdapter(new FlyoutMenuView.ArrayAdapter<>(menuItems));  //实现GridLayout添加view


        final EmojiFlyoutMenu.ButtonRenderer renderer = new EmojiFlyoutMenu.ButtonRenderer(emojiCodes[0], fontSizeInButton, color);
        smileyFlyoutMenu.setButtonRenderer(renderer);

        smileyFlyoutMenu.setSelectionListener(new FlyoutMenuView.SelectionListener() {
            @Override
            public void onItemSelected(FlyoutMenuView flyoutMenuView, FlyoutMenuView.MenuItem item) {
                smileyFlyoutMenuSelectionId = item.getId();
                renderer.setEmojiCode(((EmojiFlyoutMenu.MenuItem) item).getEmojiCode());  //设置button的内容
            }

            @Override
            public void onDismissWithoutSelection(FlyoutMenuView flyoutMenuView) {
            }
        });

    }

    public float getBrushSize() {
        return brushSize;
    }

    public void setBrushSize(float brushSize) {
        this.brushSize = brushSize;
        updateBrushStateTextView();
    }

    public boolean isBrushEraser() {
        return brushIsEraser;
    }

    public void setBrushIsEraser(boolean brushIsEraser) {
        this.brushIsEraser = brushIsEraser;
        updateBrushStateTextView();
    }

    public int getBrushColor() {
        return brushColor;
    }

    public void setBrushColor(int brushColor) {
        this.brushColor = brushColor;
        updateBrushStateTextView();
    }

    void updateBrushStateTextView() {
        String brushSizeStr = String.format("%.2f", getBrushSize());

        if (isBrushEraser()) {
            brushStateTextView.setText("Eraser size: " + brushSizeStr);
        } else {
            String colorStr = String.format("#%06X", 0xFFFFFF & getBrushColor());
            brushStateTextView.setText("Brush size: " + brushSizeStr + " color: " + colorStr);
        }
    }
}
